<?php
declare (strict_types = 1);
namespace app\mall\model;
use think\Model;

use app\common\model\BaseModel;
//use think\model\concern\SoftDelete;

Class Activity extends BaseModel
{
//    use SoftDelete;
    // 软删除字段
//    protected $deleteTime = 'delete_time';
    // 软删除 默认值
//    protected $defaultSoftDelete = 0;

    public $field = 'id,name,cover,rule,sort,hours,title,share,num,type,content,add_time,participate_num,goods,end_time,desc,btn_str,detailsImg';

    // 预处理数据
    public function getNameAttr($value){
        return emojiDecode($value);
    }

    // 预处理数据
    public function getDescAttr($value){
        return emojiDecode($value);
    }

    //    预处理数据处理 分享图
    // public function getCoverAttr($value)
    // {
    //     //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
    //     return env('app.host_domin').'://'.env('app.static_host').$value;
    // }

    //    预处理数据处理 分享图
    // public function getShareAttr($value)
    // {
    //     return env('app.host_domin').'://'.env('app.static_host').$value;
    // }

    public function getContentAttr($value)
    {
        return $value ? json_decode($value,true) : [];
    }

    public function getRuleAttr($value)
    {
        return htmlspecialchars_decode($value,ENT_QUOTES);
    }

    public function getGoodsAttr($value)
    {
        return $value ? explode(',',$value) : [$value];
    }

    // 拿取数据
    public function getList($get)
    {
        $oredr = 'sort desc';
        if(isset($get['orderKey']) && in_array($get['orderKey'],['sales_volume','default_discount_price','add_time']))
            $oredr = $get['orderKey']." ".(isset($get['order']) && in_array($get['order'],['desc','asc']) ? $get['order'] : 'desc');
        $field = 'id,name,cover,title,add_time,participate_num,end_time,btn_str';
        $where = $this->getDefaultWhere();
        $where[] = [
            'end_time','>',time()
        ];
        $this->queryList($get,$this->field,$where,$oredr);
    }

    /**
     * @param $id 查询当前id，并进行判断数据
     * @return array|null|Model|void 返回当前记录
     */
    public function getOne($id){
        if(!$id || $id < 1)
            return retu_json(400,'列表记录为空');
        $one = $this->where($this->getDefaultWhere())->field($this->field)->find($id);
        if(!$one || !$one->goods)
            return retu_json(400,'没有该记录或者活动时间已过'); 
        $time = time();    
        if($one->end_time < $time)return retu_json(400,'抱歉，当前活动已结束');
        // 拿取商品开始
        $goodsField = 'id,name,share,title,default_price,default_discount_price,sort,is_activity,sales_volume';
        $goods = (new Goods())->where([
            ['status','=',1],
            ['id','in',$one->goods]
        ])->field($goodsField)->select();

        // 根据排序进行返回数据
        $key_goods = [];
        foreach($goods as $item)$key_goods[$item['id']] = $item;
        $new_goods = [];
        foreach($one->goods as $i) if(isset($key_goods[$i])) $new_goods[] = $key_goods[$i];

        return [
            'activity' => $one,
            'goods'=> $new_goods
        ];
    }

    /**
     * 活动规则详情查看
     */
    public function getOneRule($id){
        if(!$id || $id < 1)
            return retu_json(400,'列表记录为空');
        $one = $this->where($this->getDefaultWhere())->field('id,rule')->find($id);
        return $one;
    }

    /**
     * 根据活动id和商品id进行返回
     */
    public function getActivitys($activityId,$goodsId){
        $activityModel = $this->find($activityId);
        if(!$activityModel)
            return ['code' => 400,'msg'=>'没有该拼团列表'];
        if($activityModel->status != 1)
            return ['code' => 400,'msg'=>'此拼团已下架'];
        if(!$activityModel->goods || !in_array($goodsId,$activityModel->goods))
            return ['code' => 400,'msg'=>'此活动没有该商品'];
        return ['code'=>200,'model'=> $activityModel];
    }

    /**
     * 根据商品id找到 拼团列表  没有则返回false
     */
    public function getActivitysGoods($goodsId)
    {
        $allList = $this->select();
        $model = false;
        foreach($allList as $item){
            if($item['goods'] && in_array($goodsId,$item['goods'])){
                $model = $item;
                break;
            }
        }
        return $model;
    }

    /**
     * 获取到默认查询数组
     * @return array []
     */
    public function getDefaultWhere(){
        return [
            ['status','=',1]
        ];
    }

    /**
     * 获取分享页面信息
     * @param $id  活动id
     * @return array name,cover
     */
    public function getShareGroup($id,$uid){
        try{
            if(empty($id)) exception('找不到该活动!');
            $where = [['a.id','=',$id],['a.status','=',1],['a.is_delete','=',0],['al.uid','=',$uid],['al.astatus','=',0],['al.is_delete','=',0],['al.end_time','>',time()]];
            $ret = $this->alias('a')->join('activity_log al','al.aid=a.id','left')->where($where)->field('a.name,a.title,a.share,count(al.id) as al_num')->find();
            if(!empty($ret)){
                if($ret['al_num']<1) exception('没有参与该活动无法分享!');
            }
            return $ret?$ret->toArray():[];
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }
}